# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from scrapy.pipelines.images import ImagesPipeline
import scrapy
# 指定版本下载pip install pillow==9.4.0
# 卸载模块 pip uninstall xxx

# 使用了requests,会变成同步，速度变慢
"""
import requests


class ImageSpiderPipeline:
    def process_item(self, item, spider):
        title = item["href"].split("/")[-1]
        with open(r"E:\gitcode\python-full-stack\spider\15.scrapy实战二\image_spider\image_spider\image/" + title , "wb")as f:
            resp = requests.get(item["href"]).content
            f.write(resp)
        print(title, "保存成功")
        return item
"""


class ImageSpiderPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        yield scrapy.Request(item["href"])

    def file_path(self, request, response=None, info=None, *, item=None):
        title = item["href"].split("/")[-1]
        print(title, "---保存成功")
        return title
